import { defineStore } from 'pinia'
import { getAuth, getTokens } from '@/api/servers/login'
import AsynchronousRoutings from '@/router/asynchronousRouting'
import filterRoutesByPermission from '@/utils/filterRoutes.js'
import router from '@/router/index'

export const userInfoStore = defineStore('userInfo', {
  state: () => {
    return {
      userInfo: {},
      tokens: localStorage.getItem('token') || '',
      userMenu: [],
      userPermissions: []
    }
  },
  getters: {},
  actions: {
    async getUserMenu(data) {
      const res = await getAuth(data)
      this.userMenu = res.roles

      // 权限列表
      const routes = filterRoutesByPermission(AsynchronousRoutings, res.roles)
      this.userMenu = routes
      // 动态路由
      routes.forEach(route => {
        router.addRoute(route)
      })
    },
    async getTokens(data) {
      const res = await getTokens(data)
      localStorage.setItem('token', JSON.stringify(res.token))
    }
  }
})
